import { nextTick, ref, Ref, watch } from 'vue';
import type { TableInstance } from 'element-plus';

export default function useTableSelection(tableData: Ref<any[]>, tableRef: Ref<TableInstance | undefined>, rowKey = 'id') {
  // 当前已选中的数据
  const multipleSelection = ref<any[]>([]);

  /** 当用户手动勾选数据行的 Checkbox 时触发的事件 */
  const handleSelectChange = (selection: any[], row: any) => {
    let selected = selection.length && selection.indexOf(row) !== -1;
    if (selected) {
      multipleSelection.value.push(row);
    } else {
      const selectIndex = multipleSelection.value.findIndex((item) => item[rowKey] == row[rowKey]);
      multipleSelection.value.splice(selectIndex, 1);
    }
  };

  /** 当用户手动勾选全选 Checkbox 时触发的事件 */
  const handleSelectAll = (selection: any[]) => {
    if (selection.length > 0) {
      selection.forEach((item: any) => {
        const selected = multipleSelection.value.some((it) => item[rowKey] == it[rowKey]);
        if (!selected) {
          multipleSelection.value.push(item);
        }
      })
    } else {
      multipleSelection.value = multipleSelection.value.filter((item) => tableData.value.every((it) => it[rowKey] != item[rowKey]));
    }
  };

  const setTableSelection = () => {
    const ref = tableRef.value;
    if (!ref) {
      return;
    }
    ref.data.forEach((data) => {
      const selected = multipleSelection.value.some((item) => data[rowKey] === item[rowKey],);
      ref.toggleRowSelection(data, selected);
    });
  };

  const clearSelection = (clearKeys?: any[]) => {
    tableRef.value?.clearSort();
    if (!multipleSelection.value || multipleSelection.value.length == 0) {
      return;
    }
    if (!clearKeys || clearKeys.length == 0) {
      // 全部清理
      multipleSelection.value = [];
      setTableSelection();
    } else {
      // 清理部分key
      multipleSelection.value = multipleSelection.value.filter((item) => !clearKeys.includes(item[rowKey]));
    }
  };

  watch(
    () => tableData.value,
    () => {
      nextTick(() => setTableSelection());
    },
  );

  return {
    handleSelectChange,
    handleSelectAll,
    multipleSelection,
    clearSelection,
  };
}
